#include "talk.h"


int __write(const char *file, const char *opcode)
{
	int fd;

	fd = open(file, O_WRONLY);	//opening one try


	if (fd == -1) {
		elog_err_print_console
		    ("Unable to communicate with other process:\n");
		if (fd == -1)
			elog_err_print_console
			    ("  No other running process.");
		return 1;
	}
	int written = 0;

	if ((written = write(fd, opcode, ELOG_LSN_MSG_SIZE)) < 0) {
		elog_err_print_console("Unable to write message!\n");
		return 2;
	}


	close(fd);
	return 0;
}


int elog_tlk_say(const char *file, const char *msg)
{
	char *opcode = elog_xml_start("<mesg>", ELOG_LSN_MSG_SIZE);
	elog_xml_printf(opcode, "<mesg>.%s", "<type>",
			ELOG_LSN_TYPE_COMMAND);
	elog_xml_printf(opcode, "<mesg>.%s", "<body>", msg);


	int result = __write(file, opcode);
	if (result)
		elog_err_print("Error saying message to other process\n");

	free(opcode);

	return result;
}
int elog_tlk_ask(const char *file, char **msg)
{
	char *opcode = elog_xml_start("<mesg>", ELOG_LSN_MSG_SIZE);
	elog_xml_printf(opcode, "<mesg>.%s", "<type>",
			ELOG_LSN_TYPE_FETCH);

	int result = __write(file, opcode);
	if (result) {
		elog_err_print("An error occured asking\n");
		return result;
	}

	char *file1;
	elog_sp_cat(&file1, file, "1", NULL);

	char *xml = elog_lsn_listen(file1);
	elog_xml_scanf(xml, "<mesg>.<body>.%s", msg);	//getting message.


	free(file1);

	free(opcode);
	return result;
}
int elog_tlk_reply(const char *file, char *msg)
{
	int len = strlen(msg);
	int atatime = ELOG_LSN_MSG_SIZE - 192;	//for overhead tags
	int c = 0;
	for (; c < len; c += (atatime)) {
		char *chunk = malloc((sizeof *chunk) * (atatime + 1));
		chunk[0] = '\0';
		if (c + atatime > len)	//edge case
			strncat(chunk, &(msg[c]), len - c);
		else
			strncat(chunk, &(msg[c]), atatime);

		char *tmp;
		elog_sp_cat(&tmp, "|", chunk, "|", NULL);
		free(chunk);
		chunk = tmp;	//protecting whitespace


		char *opcode =
		    elog_xml_start("<mesg>", ELOG_LSN_MSG_SIZE + 1);
		int i;
		for (i = 1024; i < ELOG_LSN_MSG_SIZE; ++i)
			opcode[i] = '\0';
		elog_xml_printf(opcode, "<mesg>.%s", "<type>",
				ELOG_LSN_TYPE_REPLY);
		elog_xml_printf(opcode, "<mesg>.%s", "<body>", chunk);
		if (c + atatime > len)
			elog_xml_printf(opcode, "<mesg>.%s", "<done>",
					"DONE");


		int result = __write(file, opcode);
		if (result) {
			elog_err_print_console
			    ("An error occured responding to a request from ejourn\n");
			return result;
		}
		free(chunk);

		free(opcode);

	}
	return 0;
}
